package cn.micai.base.asyn;

import java.util.concurrent.*;

/**
 * 描述：通过FutureTask实现
 *
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/11 13:35
 */
public class FutureDemo1 {

    public static void main(String [] args) throws ExecutionException, InterruptedException {

        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return new RealDate().costTime();
            }
        });

        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(future);

        System.out.println("RealData方法调用完毕");
        // 模拟主函数中其他耗时操作
        doOtherThing();
        // 获取RealData方法的结果
        System.out.println(future.get());
    }

    private static void doOtherThing() {
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class RealDate {
        public String costTime() {
            try {
                // 模拟RealData耗时操作
                Thread.sleep(1000);
                return "result";
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "exception";
        }
    }

}
